/**
 * Created by LeungZ on 2016/8/10.
 */
import ctrl from './form/replicas.ctrl.js';
import tmp from './form/replicas.html';

class Detail {
    constructor(detail, $uiModal, serviceSrv, ctgNotification, $scope, $stateParams) {
        "ngInject";
        this._uiModal = $uiModal;
        this._serviceSrv = serviceSrv;
        this._ctgNotification = ctgNotification;
        this._scope = $scope;
        this.dbCode = $stateParams.kDbCode;
        this.name = $stateParams.name;
        this.namesp = $stateParams.namesp;
        this.appId = $stateParams.appId;

        if (detail) {
            this.images = detail.containerImages;
            this.selector = this.mapToArray(detail.labelSelector);
            this.labels = this.mapToArray(detail.labels);
            this.podInfo = detail.podInfo;
        }
    }

    mapToArray(map) {
        let array = [];
        angular.forEach(Object.keys(map), function (ele) {
            array.push(ele + '=' + map[ele]);
        });
        return array;
    }

    infoRefresh() {
        if (this.infoLoading) return;

        this._scope.$broadcast("updateRCPodList");
        this.infoLoading = true;
        this._serviceSrv.getRCDetail({
            namesp: this.namesp,
            name: this.name,
            code: this.dbCode
        }).then(data => {
            this.podInfo = data.podInfo;
        }).catch(data=> {
            this._ctgNotification.error('获取RC容器概况数据有误.');
        }).finally(()=> {
            this.infoLoading = false;
        });
    }

    changeReplicas(name, podInfo) {
        if (this.infoLoading || !podInfo) return;

        this._uiModal.open({
            animation: true,
            templateUrl: tmp,
            controller: ctrl,
            controllerAs: 'vm',
            resolve: {
                replicas: function () {
                    return {
                        name: name,
                        podCreated: podInfo.current,
                        podDesired: podInfo.desired
                    };
                }
            }
        }).result.then(replicas=> {
                this.infoLoading = true;
                this._serviceSrv.updateReplicas({
                    namesp: this.namesp,
                    name: this.name,
                    replicas: parseInt(replicas),
                    code: this.dbCode
                }).then(data=> {
                    this.podInfo.desired = data.replicas;
                    this._ctgNotification.success('修改RC扩缩容成功.');
                }).catch(data=> {
                    this._ctgNotification.error('修改RC扩缩容失败.');
                }).finally(()=> {
                    this.infoLoading = false;
                });
            });
    }
}
export default Detail